﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using VietThinks.Web.Mvc;
using VietThinks.Website.ActionFilter;

namespace VietThinks.Website.Controllers
{
    [HandleErrorExAspect, ValidateInput(false), LogInformationActionRequest]
    public abstract class ApplicationController : Controller
    {
        protected virtual void AddBrokenRulesToModelState(IEnumerable<string> rules)
        {
            foreach (var rule in rules)
            {
                this.ModelState.AddModelError(rule, rule);
            }
        }

        protected override void HandleUnknownAction(string actionName)
        {
            this.RedirectToAction<ErrorController>(c => c.UnresolvableRequest(this.Request.Url.AbsoluteUri))
                .ExecuteResult(this.ControllerContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.ExceptionHandled = true;

                var signaledError = filterContext.Exception is HttpException
                    ? filterContext.Exception
                    : new HttpException((int)HttpStatusCode.InternalServerError, filterContext.Exception.Message, filterContext.Exception);

                if (!filterContext.HttpContext.IsCustomErrorEnabled)
                {
                    this.TempData["Description"] = filterContext.Exception.Message;
                    this.TempData["Source"] = filterContext.Exception.Source;
                    this.TempData["StackTrace"] = filterContext.Exception.StackTrace;
                }

                while (signaledError.InnerException != null)
                {
                    signaledError = signaledError.InnerException;
                }

                Elmah.ErrorSignal.FromCurrentContext().Raise(signaledError);

                this.RedirectToAction<ErrorController>(c => c.Show())
                    .ExecuteResult(this.ControllerContext);
            }
        }

        // used for (dialog) partial view to prevent IE's stupid caching mechanism
        protected void SetNoCacheHeaders()
        {
            this.Response.CacheControl = "no-cache";
            this.Response.Cache.SetExpires(DateTime.MinValue);
            this.Response.Cache.SetNoStore();
            this.Response.Cache.SetNoServerCaching();
        }
    }
}
